<?php
require_once '../library/Auth/OpenID/Consumer.php';
require_once '../library/Auth/OpenID/FileStore.php';
require_once '../library/Auth/OpenID/SReg.php';

class MCore_SSO {
	
	public function checkLoginStatus($url, $uid, $sid){
		$state = false;
		$res = $this->postData($url.'/login/state.xml', $uid, $sid);
		if(!empty($res['state']) && !empty($res['uid']) && $res['state'] == "true"){
			$state = true;
		}
		return $state;
	}
	public function checkSSO($openidIdentifier, $returnLink, $sregRequireParams = null, $sregOptionalParams = null) {
	    $openid = $openidIdentifier;
	    $consumer = $this->getConsumer();

	    // Begin the OpenID authentication process.
	    $auth_request = $consumer->begin($openid);

	    // No auth request means we can't begin OpenID.
	    if (!$auth_request) {
	        return "Authentication error; not a valid OpenID.";
	    }

	    $sreg_request = Auth_OpenID_SRegRequest::build(
	                                     // Required
	                                     $sregRequireParams,
	                                     // Optional
	                                     $sregOptionalParams,"http://www.policy-url.com");

	    if ($sreg_request) {
	        $auth_request->addExtension($sreg_request);
	    }

		$policy_uris = null;
		if (isset($_GET['policies'])) {
	    	$policy_uris = $_GET['policies'];
		}

	    // $pape_request = new Auth_OpenID_PAPE_Request($policy_uris);
	    // if ($pape_request) {
	    //     $auth_request->addExtension($pape_request);
	    // }

	    // Redirect the user to the OpenID server for authentication.
	    // Store the token for this authentication so we can verify the
	    // response.

	    // For OpenID 1, send a redirect.  For OpenID 2, use a Javascript
	    // form to send a POST request to the server.
	    if ($auth_request->shouldSendRedirect()) {
	        $redirect_url = $auth_request->redirectURL($this->getTrustRoot($returnLink),
	                                                   $this->getReturnTo($returnLink));

	        // If the redirect URL can't be built, display an error
	        // message.
	        if (Auth_OpenID::isFailure($redirect_url)) {
	            return "Could not redirect to server: " . $redirect_url->message;
	        } else {
	            // Send redirect.
	            header("Location: ".$redirect_url);
	        }
	    } else {
	        // Generate form markup and render it.
	        $form_id = 'openid_message';
	        $form_html = $auth_request->htmlMarkup($this->getTrustRoot($returnLink), $this->getReturnTo($returnLink),
	                                               false, array('id' => $form_id));

	        // Display an error if the form markup couldn't be generated;
	        // otherwise, render the HTML.
	        if (Auth_OpenID::isFailure($form_html)) {
	            return "Could not redirect to server: " . $form_html->message;
	        } else {
	            print $form_html;
	        }
	    }
	    return "";
	}

	public function complete($returnLink, $sregRequireParams = null, $sregOptionalParams = null) {
	    $consumer = $this->getConsumer();

	    // Complete the authentication process using the server's
	    // response.
	    $return_to = $this->getReturnTo($returnLink);
	    $response = $consumer->complete($return_to);

	    $msg = "";
	    $data = array();
	    // Check the response status.
	    if ($response->status == Auth_OpenID_CANCEL) {
	        // This means the authentication was cancelled.
	        $msg = 'Verification cancelled.';
	    } else if ($response->status == Auth_OpenID_FAILURE) {
	        // Authentication failed; display the error message.
	        $msg = "OpenID authentication failed: " . $response->message;
	    } else if ($response->status == Auth_OpenID_SUCCESS) {
	        // This means the authentication succeeded; extract the
	        // identity URL and Simple Registration data (if it was
	        // returned).
	        $openid = $response->getDisplayIdentifier();
	        $esc_identity = $this->escape($openid);

	        $uid = substr($esc_identity, $this->getLastMath($esc_identity, '/') + 1 );
	        $data['uid'] = $uid;
	        $sid = $_GET['sid'];
	        $data['sid'] = $sid;
	        // if ($response->endpoint->canonicalID) {
	        //     $escaped_canonicalID = $this->escape($response->endpoint->canonicalID);
	        //     $success .= '  (XRI CanonicalID: '.$escaped_canonicalID.') ';
	        // }

	        $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);

	        $sreg = $sreg_resp->contents();

	        if(!empty($sregRequireParams)){
	        	$requireCheck = true;
	        	foreach($sregRequireParams as $param){
			        if (isset($sreg[$param]) && @$sreg[$param]) {
			        	$data[$param] = $this->escape($sreg[$param]);
			        }else{
			        	$requireCheck = false;
			        }	        		
	        	}
	        	if(!$requireCheck){
	        		$msg = "Don't have required data";
	        	}
	        }

	        if(!empty($sregOptionalParams)){
	        	foreach($sregOptionalParams as $param){
			        if (isset($sreg[$param]) && @$sreg[$param]) {
			        	$data[$param] = $this->escape($sreg[$param]);
			        }	        		
	        	}
	        }

	    }

	    $return = array('msg' => $msg, 'data' => $data);
	    return $return;
	}

	function escape($thing) {
	    return htmlentities($thing);
	}

	function &getStore() {
	    /**
	     * This is where the example will store its OpenID information.
	     * You should change this path if you want the example store to be
	     * created elsewhere.  After you're done playing with the example
	     * script, you'll have to remove this directory manually.
	     */
	    $store_path = null;

	    $store_path = dirname($_SERVER['DOCUMENT_ROOT']).'/tmp';
	    $store_path .= DIRECTORY_SEPARATOR . '_php_consumer_test';

	    if (!file_exists($store_path) &&
	        !mkdir($store_path)) {
	        print "Could not create the FileStore directory '$store_path'. ".
	            " Please check the effective permissions.";
	        exit(0);
	    }

		$r = new Auth_OpenID_FileStore($store_path);

	    return $r;
	}


	function &getConsumer() {
	    /**
	     * Create a consumer object using the store object created
	     * earlier.
	     */
	    $store = $this->getStore();
		$r = new Auth_OpenID_Consumer($store);
	    return $r;
	}
	function getScheme() {
	    $scheme = 'http';
	    if (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') {
	        $scheme .= 's';
	    }
	    return $scheme;
	}

	function getReturnTo($returnLink) {
	    return sprintf("%s://%s:%s%s",
	                   $this->getScheme(), $_SERVER['SERVER_NAME'],
	                   $_SERVER['SERVER_PORT'],
	                   $returnLink);
       
	}

	function getTrustRoot($returnLink) {
	    return sprintf("%s://%s:%s%s",
	                   $this->getScheme(), $_SERVER['SERVER_NAME'],
	                   $_SERVER['SERVER_PORT'],
	                   $returnLink);

	}

	function getLastMath($str, $subStr){
		$offset = 0; // initial offset is 0
		$counter = 0;
		$pos = -1;

		if(strpos($str, $subStr) == 0){
			$pos = $offset;
			$counter++;
		}

		// Check the rest of the string for 5's
		while($offset = strpos($str, $subStr, $offset + 1)){
			$pos = $offset;
			$counter++;
		}

		return $pos;
	}

    function postData($url, $uid, $sid)
    {
    	$result = "";
		$client = new Zend_Http_Client($url);
		$client->setParameterPost(array(
		    'uid' => $uid,
		    'sid' => $sid
		));
		$response = $client->request('POST');
		$result = $this->XML2Array($response->getBody());
		return $result;
    }

	function XML2Array ( $xml , $recursive = false )
	{
	    if ( ! $recursive )
	    {
	        $array = simplexml_load_string ( $xml ) ;
	    }
	    else
	    {
	        $array = $xml ;
	    }
	    
	    $newArray = array () ;
	    $array = ( array ) $array ;
	    foreach ( $array as $key => $value )
	    {
	        $value = ( array ) $value ;
	        if ( isset ( $value [ 0 ] ) )
	        {
	            $newArray [ $key ] = trim ( $value [ 0 ] ) ;
	        }
	        else
	        {
	            $newArray [ $key ] = $this->XML2Array ( $value , true ) ;
	        }
	    }
	    return $newArray ;
	}    

}
?>